﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.UI;
using System.Web.UI.WebControls;
using Controllers;
using CuteWebUI;

namespace Web
{
    public partial class CardLog : System.Web.UI.Page
    {
        protected string cardLogs;
        protected void Page_Load(object sender, EventArgs e)
        {
            EmpBasicInfo ebi = Session["ebi"] as EmpBasicInfo;
            if (ebi.EmpRoles.Where(r => r.RoleId == 1).Any())//超级管理员角色
            {
                UploaderFile.Visible = true;
                btnSetDate.Visible = true;
            }
            if (!IsPostBack)
            {
                ApolloOaDataContext ctx = new ApolloOaDataContext(ConfigurationManager.ConnectionStrings["SqlConnectionString"].ConnectionString);
                var v = ctx.EmpDepPositions.Where(r => r.EmpId == ebi.Id && r.PosId <= 3);
                var v2 = from r in ctx.EmpRoles where r.EmpId == ebi.Id join r2 in ctx.RoleControllerDepts on r.RoleId equals r2.RoleId where r2.DeptId == null && (r2.Controller == "Card" || r2.Controller == null) select 0;
                string strSql;
                if (v.Count() > 0 || v2.Count() > 0 || ebi.EmpRoles.Where(r => r.RoleId == 1).Any())
                {
                    strSql = @"with t as (select Id,Pid,cast(Text as nvarchar(500)) Text,OrderNo,1 lvl,cast(Id as nvarchar(50)) orderStr from Depts where Pid is null
union all
select d.Id,d.Pid,cast(REPLICATE('--',t.lvl)+d.Text as nvarchar(500)),
d.OrderNo,t.lvl+1,cast(t.orderStr+cast(d.Id as nvarchar(50)) as nvarchar(50))
from Depts d,t where d.Pid=t.id and d.IsValid=1
)
  select Id,Text from t order by orderStr;";
                }
                else
                {
                    strSql = string.Format(@"with t as(
SELECT b.Id,b.Text FROM EmpDepPositions a,Depts b where a.DeptId=b.Id and a.PosId<=7 and a.EmpId={0}
union all
select isnull(c.Id,1),isnull(c.Text,'太阳神直销总部') from EmpRoles a
	inner join RoleControllerDepts b on a.RoleId=b.RoleId and a.EmpId={0} and (b.Controller='{1}' or b.Controller is null)
	left join Depts c on b.DeptId=c.Id
union all
select a.Id,a.Text from Depts a,t where a.Pid=t.Id and a.IsValid=1
)
select distinct Id,Text from t;", ebi.Id, "Card");
                }
                var depts = ctx.ExecuteQuery<DeptDTO>(strSql);
                ddlDept.DataSource = depts;
                ddlDept.DataValueField = "Id";
                ddlDept.DataTextField = "Text";
                ddlDept.DataBind();
                ddlDept.Items.Insert(0, new ListItem("", ""));
                DateTime eDate = DateTime.Today;
                endDate.Value = eDate.ToString("yyyy-MM-dd");
                DateTime sDate = new DateTime(eDate.Year, eDate.Month, 1);
                startDate.Value = sDate.ToString("yyyy-MM-dd");
                _getDatas();
            }
        }
        protected void btnSeach_ServerClick(object sender, System.EventArgs e)
        {
            _getDatas();
        }

        private void _getDatas()
        {
            string deptId = ddlDept.Value;
            if (string.IsNullOrEmpty(deptId))
            {
                EmpBasicInfo ebi = Session["ebi"] as EmpBasicInfo;
                deptId = "EmpId" + ebi.Id;
            }
            DateTime sDate = DateTime.Parse(startDate.Value);
            DateTime eDate = DateTime.Parse(endDate.Value);
            if (eDate.Subtract(sDate).Days > 31)
            {
                // Define the name and type of the client script on the page.
                String csName = "WarningScript";
                Type csType = this.GetType();

                // Get a ClientScriptManager reference from the Page class.
                ClientScriptManager cs = Page.ClientScript;

                // Check to see if the client script is already registered.
                if (!cs.IsClientScriptBlockRegistered(csType, csName))
                {
                    StringBuilder csText = new StringBuilder();
                    csText.Append(@"<script>alert('开始/结束 日期最多能相差一月(31天).');</script>");
                    cs.RegisterClientScriptBlock(csType, csName, csText.ToString());
                }
            }
            else
            {
                CardController cardController = new CardController();
                cardLogs = cardController.Find(deptId, sDate, eDate);
            }
        }

        protected void Uploader_File(object sender, UploaderEventArgs args)
        {
            string m_path = Server.MapPath(@"~\TempFile\");
            int dotIndex = args.FileName.LastIndexOf('.');
            string fileExt = args.FileName.Substring(dotIndex);

            string saveFileName = DateTime.Now.ToString("yyyyMMddhhmmss") + "CardLog." + fileExt;
            string savePath = m_path + saveFileName;
            args.MoveTo(savePath);

            IExcel tmp = ExcelLib.GetExcel(savePath);

            try
            {
                //tmp.CurrentSheetIndex =0;
                tmp.Open();
                int rowCnt = tmp.GetRowCount();
                IList<Controllers.CardLog> cardLogs = new List<Controllers.CardLog>();
                ApolloOaDataContext ctx = new ApolloOaDataContext(ConfigurationManager.ConnectionStrings["SqlConnectionString"].ConnectionString);
                for (int i = 0; i < rowCnt; i++)
                {
                    string currJobNo = tmp.GetCellValue(i, 0).Trim();
                    if (Regex.IsMatch(currJobNo, @"^\d{3,}$"))
                    {
                        Controllers.CardLog obj = new Controllers.CardLog();
                        if (currJobNo.Length > 3)
                        {
                            currJobNo = currJobNo.Substring(currJobNo.Length - 3);
                        }
                        obj.JobNo = "SZAP" + currJobNo;
                        obj.CardTime = DateTime.Parse(tmp.GetCellValue(i, 3) + " " + tmp.GetCellValue(i, 4) + ":00");
                        EmpBasicInfo ebi = Session["ebi"] as EmpBasicInfo;
                        obj.OperateId = ebi.Id;
                        obj.SysDate = DateTime.Now;
                        cardLogs.Add(obj);
                    }
                }
                ctx.CardLogs.InsertAllOnSubmit(cardLogs);
                ctx.SubmitChanges();
                tmp.Close();
            }
            catch (Exception ex)
            { }
            System.IO.File.Delete(savePath);//删除
            _getDatas();
        }
    }
}